package service

import (
	"fmt"
	"time"

	"gitee.com/wangshh_123/cross-pay-go/src/database"
	"gitee.com/wangshh_123/cross-pay-go/src/models"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/common"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// DepartmentService 部门服务
type DepartmentService struct{}

// NewDepartmentService 创建部门服务实例
func NewDepartmentService() *DepartmentService {
	return &DepartmentService{}
}

// CreateDepartment 创建部门
func (s *DepartmentService) CreateDepartment(ctx *gin.Context, req *models.DepartmentCreateRequest, userID int64) (*models.Department, error) {
	// 检查部门编码是否已存在
	var existingDept models.Department
	if err := database.DB.Where("code = ? AND deleted_at IS NULL", req.Code).First(&existingDept).Error; err == nil {
		return nil, fmt.Errorf("DEPARTMENT_CODE_EXISTS")
	}

	// 创建部门
	department := &models.Department{
		Name:        req.Name,
		Code:        req.Code,
		Description: &req.Description,
		Status:      "active",
		CreatedBy:   userID,
		UpdatedBy:   userID,
	}

	if err := database.DB.Create(department).Error; err != nil {
		return nil, fmt.Errorf("DATABASE_ERROR: %v", err)
	}

	return department, nil
}

// UpdateDepartment 更新部门
func (s *DepartmentService) UpdateDepartment(ctx *gin.Context, id int64, req *models.DepartmentUpdateRequest, userID int64) (*models.Department, error) {
	// 检查部门是否存在
	var department models.Department
	if err := database.DB.Where("id = ? AND deleted_at IS NULL", id).First(&department).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("DEPARTMENT_NOT_FOUND")
		}
		return nil, fmt.Errorf("DATABASE_ERROR: %v", err)
	}

	// 检查部门编码是否已被其他部门使用
	var existingDept models.Department
	if err := database.DB.Where("code = ? AND id != ? AND deleted_at IS NULL", req.Code, id).First(&existingDept).Error; err == nil {
		return nil, fmt.Errorf("DEPARTMENT_CODE_EXISTS")
	}

	// 更新部门
	updates := map[string]interface{}{
		"name":        req.Name,
		"code":        req.Code,
		"description": req.Description,
		"status":      req.Status,
		"updated_by":  userID,
		"updated_at":  time.Now(),
	}

	if err := database.DB.Model(&department).Updates(updates).Error; err != nil {
		return nil, fmt.Errorf("DATABASE_ERROR: %v", err)
	}

	// 重新查询更新后的部门
	if err := database.DB.Where("id = ?", id).First(&department).Error; err != nil {
		return nil, fmt.Errorf("DATABASE_ERROR: %v", err)
	}

	return &department, nil
}

// DeleteDepartment 删除部门
func (s *DepartmentService) DeleteDepartment(ctx *gin.Context, id int64, userID int64) error {
	// 检查部门是否存在
	var department models.Department
	if err := database.DB.Where("id = ? AND deleted_at IS NULL", id).First(&department).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return fmt.Errorf("DEPARTMENT_NOT_FOUND")
		}
		return fmt.Errorf("DATABASE_ERROR: %v", err)
	}

	// 检查部门是否有关联的用户
	var count int64
	if err := database.DB.Model(&models.DepartmentUser{}).Where("department_id = ? AND status = 'active'", id).Count(&count).Error; err != nil {
		return fmt.Errorf("DATABASE_ERROR: %v", err)
	}

	if count > 0 {
		return fmt.Errorf("DEPARTMENT_HAS_USERS")
	}

	// 软删除部门
	now := time.Now()
	updates := map[string]interface{}{
		"deleted_at": &now,
		"updated_by": userID,
		"updated_at": now,
	}

	if err := database.DB.Model(&department).Updates(updates).Error; err != nil {
		return fmt.Errorf("DATABASE_ERROR: %v", err)
	}

	return nil
}

// GetDepartmentList 获取部门列表
func (s *DepartmentService) GetDepartmentList(ctx *gin.Context, req *models.DepartmentListRequest) (*common.PaginationResult, error) {
	var departments []models.Department
	var total int64

	query := database.DB.Model(&models.Department{}).Where("deleted_at IS NULL")

	// 添加查询条件
	if req.Name != "" {
		query = query.Where("name LIKE ?", "%"+req.Name+"%")
	}
	if req.Code != "" {
		query = query.Where("code LIKE ?", "%"+req.Code+"%")
	}
	if req.Status != "" {
		query = query.Where("status = ?", req.Status)
	}

	// 统计总数
	if err := query.Count(&total).Error; err != nil {
		return nil, fmt.Errorf("DATABASE_ERROR: %v", err)
	}

	// 分页查询
	offset := (req.Page - 1) * req.PageSize
	if err := query.Offset(offset).Limit(req.PageSize).
		Preload("CreatedByUser").
		Preload("UpdatedByUser").
		Order("created_at DESC").
		Find(&departments).Error; err != nil {
		return nil, fmt.Errorf("DATABASE_ERROR: %v", err)
	}

	// 统计每个部门的用户数量
	for i := range departments {
		if err := database.DB.Model(&models.DepartmentUser{}).Where("department_id = ? AND status = 'active'", departments[i].ID).Count(&departments[i].UserCount).Error; err != nil {
			return nil, fmt.Errorf("DATABASE_ERROR: %v", err)
		}
	}

	return &common.PaginationResult{
		Data:       departments,
		Total:      total,
		Page:       req.Page,
		PageSize:   req.PageSize,
		TotalPages: (total + int64(req.PageSize) - 1) / int64(req.PageSize),
	}, nil
}

// CreateDepartmentUser 创建部门用户关联
func (s *DepartmentService) CreateDepartmentUser(ctx *gin.Context, req *models.DepartmentUserCreateRequest, userID int64) (*models.DepartmentUser, error) {
	// 检查部门是否存在
	var department models.Department
	if err := database.DB.Where("id = ? AND deleted_at IS NULL", req.DepartmentID).First(&department).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("DEPARTMENT_NOT_FOUND")
		}
		return nil, fmt.Errorf("DATABASE_ERROR: %v", err)
	}

	// 检查用户是否存在
	var user models.User
	if err := database.DB.Where("id = ? AND is_deleted = 0", req.UserID).First(&user).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("USER_NOT_FOUND")
		}
		return nil, fmt.Errorf("DATABASE_ERROR: %v", err)
	}

	// 检查用户是否已在该部门（只查active记录）
	var existingDeptUser models.DepartmentUser
	if err := database.DB.Where("department_id = ? AND user_id = ? AND status = 'active'", req.DepartmentID, req.UserID).First(&existingDeptUser).Error; err == nil {
		return nil, fmt.Errorf("USER_ALREADY_IN_DEPARTMENT")
	}

	// 处理默认值
	joinDate := time.Now()
	if req.JoinDate != "" {
		parsedJoinDate, err := time.Parse("2006-01-02", req.JoinDate)
		if err != nil {
			return nil, fmt.Errorf("INVALID_JOIN_DATE_FORMAT")
		}
		joinDate = parsedJoinDate
	}

	status := "active"
	if req.Status != "" {
		status = req.Status
	}

	// 创建部门用户关联
	departmentUser := &models.DepartmentUser{
		DepartmentID: req.DepartmentID,
		UserID:       req.UserID,
		JoinDate:     joinDate,
		Status:       status,
		CreatedBy:    userID,
		UpdatedBy:    userID,
	}

	if err := database.DB.Create(departmentUser).Error; err != nil {
		return nil, fmt.Errorf("DATABASE_ERROR: %v", err)
	}

	return departmentUser, nil
}

// UpdateDepartmentUser 更新部门用户关联
func (s *DepartmentService) UpdateDepartmentUser(ctx *gin.Context, id int64, req *models.DepartmentUserUpdateRequest, userID int64) (*models.DepartmentUser, error) {
	// 检查部门用户关联是否存在
	var departmentUser models.DepartmentUser
	if err := database.DB.Where("id = ?", id).First(&departmentUser).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("DEPARTMENT_USER_NOT_FOUND")
		}
		return nil, fmt.Errorf("DATABASE_ERROR: %v", err)
	}

	// 解析日期
	joinDate, err := time.Parse("2006-01-02", req.JoinDate)
	if err != nil {
		return nil, fmt.Errorf("INVALID_JOIN_DATE_FORMAT")
	}

	var leaveDate *time.Time
	if req.LeaveDate != "" {
		parsedLeaveDate, err := time.Parse("2006-01-02", req.LeaveDate)
		if err != nil {
			return nil, fmt.Errorf("INVALID_LEAVE_DATE_FORMAT")
		}
		leaveDate = &parsedLeaveDate
	}

	// 更新部门用户关联
	updates := map[string]interface{}{
		"join_date":  joinDate,
		"leave_date": leaveDate,
		"status":     req.Status,
		"updated_by": userID,
		"updated_at": time.Now(),
	}

	if err := database.DB.Model(&departmentUser).Updates(updates).Error; err != nil {
		return nil, fmt.Errorf("DATABASE_ERROR: %v", err)
	}

	// 重新查询更新后的记录
	if err := database.DB.Where("id = ?", id).First(&departmentUser).Error; err != nil {
		return nil, fmt.Errorf("DATABASE_ERROR: %v", err)
	}

	return &departmentUser, nil
}

// DeleteDepartmentUser 删除部门用户关联（软删除）
func (s *DepartmentService) DeleteDepartmentUser(ctx *gin.Context, userID int64, operatorID int64) error {
	// 检查用户是否存在
	var user models.User
	if err := database.DB.Where("id = ? AND is_deleted = 0", userID).First(&user).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return fmt.Errorf("USER_NOT_FOUND")
		}
		return fmt.Errorf("DATABASE_ERROR: %v", err)
	}

	// 查找用户所有active状态的部门关联
	var departmentUsers []models.DepartmentUser
	if err := database.DB.Where("user_id = ? AND status = 'active'", userID).Find(&departmentUsers).Error; err != nil {
		return fmt.Errorf("DATABASE_ERROR: %v", err)
	}

	// 如果没有active状态的部门关联，直接返回成功
	if len(departmentUsers) == 0 {
		return nil
	}

	// 批量更新所有active状态的部门关联为inactive
	now := time.Now()
	updates := map[string]interface{}{
		"leave_date": &now,
		"status":     "inactive",
		"updated_by": operatorID,
		"updated_at": now,
	}

	if err := database.DB.Model(&models.DepartmentUser{}).
		Where("user_id = ? AND status = 'active'", userID).
		Updates(updates).Error; err != nil {
		return fmt.Errorf("DATABASE_ERROR: %v", err)
	}

	return nil
}

// GetDepartmentUserList 获取部门用户列表
func (s *DepartmentService) GetDepartmentUserList(ctx *gin.Context, req *models.DepartmentUserListRequest) (*common.PaginationResult, error) {
	var departmentUsers []models.DepartmentUser
	var total int64

	query := database.DB.Model(&models.DepartmentUser{})

	// 默认只查询active状态的用户
	if req.Status != "" {
		query = query.Where("status = ?", req.Status)
	} else {
		query = query.Where("status = ?", "active")
	}

	if req.DepartmentID > 0 {
		query = query.Where("department_id = ?", req.DepartmentID)
	}
	if req.UserID > 0 {
		query = query.Where("user_id = ?", req.UserID)
	}

	// 统计总数
	if err := query.Count(&total).Error; err != nil {
		return nil, fmt.Errorf("DATABASE_ERROR: %v", err)
	}

	// 分页查询
	offset := (req.Page - 1) * req.PageSize
	if err := query.Offset(offset).Limit(req.PageSize).
		Preload("Department").
		Preload("User").
		Preload("CreatedByUser").
		Preload("UpdatedByUser").
		Order("created_at DESC").
		Find(&departmentUsers).Error; err != nil {
		return nil, fmt.Errorf("DATABASE_ERROR: %v", err)
	}

	return &common.PaginationResult{
		Data:       departmentUsers,
		Total:      total,
		Page:       req.Page,
		PageSize:   req.PageSize,
		TotalPages: (total + int64(req.PageSize) - 1) / int64(req.PageSize),
	}, nil
}

// GetUserDepartmentHistory 获取用户部门历史
func (s *DepartmentService) GetUserDepartmentHistory(ctx *gin.Context, userID int64, page, pageSize int) ([]models.DepartmentUser, int64, error) {
	var departmentUsers []models.DepartmentUser
	var total int64

	// 统计总数
	if err := database.DB.Model(&models.DepartmentUser{}).Where("user_id = ?", userID).Count(&total).Error; err != nil {
		return nil, 0, fmt.Errorf("DATABASE_ERROR: %v", err)
	}

	// 分页查询
	offset := (page - 1) * pageSize
	if err := database.DB.Where("user_id = ?", userID).
		Preload("Department").
		Preload("User").
		Preload("CreatedByUser").
		Preload("UpdatedByUser").
		Offset(offset).Limit(pageSize).
		Order("created_at DESC").
		Find(&departmentUsers).Error; err != nil {
		return nil, 0, fmt.Errorf("DATABASE_ERROR: %v", err)
	}

	return departmentUsers, total, nil
}

// TransferDepartmentUser 用户更换部门
func (s *DepartmentService) TransferDepartmentUser(ctx *gin.Context, req *models.DepartmentUserTransferRequest, userID int64) error {
	// 检查新部门是否存在
	var newDepartment models.Department
	if err := database.DB.Where("id = ? AND deleted_at IS NULL", req.NewDepartmentID).First(&newDepartment).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return fmt.Errorf("TARGET_DEPARTMENT_NOT_FOUND")
		}
		return fmt.Errorf("DATABASE_ERROR: %v", err)
	}

	// 检查用户是否存在
	var user models.User
	if err := database.DB.Where("id = ? AND is_deleted = 0", req.UserID).First(&user).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return fmt.Errorf("USER_NOT_FOUND")
		}
		return fmt.Errorf("DATABASE_ERROR: %v", err)
	}

	// 开始事务
	tx := database.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 1. 查找用户当前活跃的部门记录，设置为inactive
	var currentDeptUser models.DepartmentUser
	if err := tx.Where("user_id = ? AND status = 'active'", req.UserID).First(&currentDeptUser).Error; err == nil {
		// 用户有当前部门，需要设置离开时间和状态
		now := time.Now()
		updates := map[string]interface{}{
			"leave_date": &now,
			"status":     "inactive",
			"updated_by": userID,
			"updated_at": now,
		}
		if err := tx.Model(&currentDeptUser).Updates(updates).Error; err != nil {
			tx.Rollback()
			return fmt.Errorf("DATABASE_ERROR: %v", err)
		}
	}

	// 2. 创建新的部门用户关联记录（每次都创建新记录）
	transferDate := time.Now()

	newDeptUser := &models.DepartmentUser{
		DepartmentID: req.NewDepartmentID,
		UserID:       req.UserID,
		JoinDate:     transferDate,
		Status:       "active",
		CreatedBy:    userID,
		UpdatedBy:    userID,
	}
	if err := tx.Create(newDeptUser).Error; err != nil {
		tx.Rollback()
		return fmt.Errorf("DATABASE_ERROR: %v", err)
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		return fmt.Errorf("DATABASE_ERROR: %v", err)
	}

	return nil
}
